import axios from "axios";
import QS from "qs"
import { tansParams } from '@/util/utils'
import { ElLoading, ElMessage } from "element-plus";
import router from '@/router/index'

let loadingInstance
const tokenKey = process.env.VUE_APP_TOKEN
const instance = axios.create({
    baseURL: process.env.VUE_APP_BASE_URL,
    timeout: 60000,
    headers: { "Content-Type": "application/json;charset=utf-8", "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Credentials": "true" }
})

// 请求拦截器
instance.interceptors.request.use(config => {
    const authorization = localStorage.getItem(tokenKey)
    if (authorization) {
        config.headers[tokenKey] = authorization
    } else {
        router.replace('/login')
    }
    if (config.method === 'get') {
        if (config.params) {
            let url = config.url + '?' + tansParams(config.params);
            url = url.slice(0, -1);
            config.params = {};
            config.url = url;
        }
    } else if (config.method === 'post') {
        if (config.params) {
            const params = typeof config.data === 'object' ? JSON.stringify(config.data) : config.data
            config.data = params
        }
    } else {
        showErrorMsg('仅支持GET/POST请求方式')
        return Promise.reject(new Error('仅支持GET/POST请求方式'))
    }
    loadingInstance = ElLoading.service({ fullscreen: true, text: "处理中，请稍候...", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
    return config
}, error => {
    loadingInstance.close()
    return Promise.error(error)
})

// 响应拦截器
instance.interceptors.response.use(rsp => {
    const code = rsp.data.code || 'S'
    const msg = rsp.data.message || '服务器繁忙'
    // 二进制直接返回
    if (rsp.request.responseType === 'blob' || rsp.request.responseType === 'arraybuffer') {
        loadingInstance.close()
        return rsp.data
    }
    loadingInstance.close()
    if (code === 'S') {
        return Promise.resolve(rsp)
    } else if (code === 'U99999') {// Token 失效
        showErrorMsg(msg)
        router.replace('/login')
    } else {
        showErrorMsg(msg)
    }
    return Promise.reject(new Error(msg))
}, error => {
    loadingInstance.close()
    showErrorMsg(error.message)
    return Promise.reject(error)
})

function showErrorMsg(msg) {
    setTimeout(() => ElMessage({ type: 'error', message: msg, showClose: true }), 10)
}

export default instance